<?php
/**
 * @package Wkernel
 */ 
require_once 'WKernel/Data/Loader/Int.php';
class WK_Data_Loader_Xml implements WK_Data_Loader_Int {
	private $data = array();
	private $path = array();
	/**
	 * (non-PHPdoc)
	 * @see WKernel/Data/Loader/WK_Data_Loader_Int::load()
	 */	
	public function load($string_data){
		$parser = new WK_Markup_Parser ($string_data, array(
			'root' => $this,
			'open' => array(
				'data' => array('method' => 'initData'),
				'*'    => array('method' => 'openNode')
			),
			'cdata' => array('*' => array('method' => 'setValue')),
			'close' => array('*' => array('method' => 'closeNode'))
		));
		$parser->run();
		return new WK_Data_Map($this->data);
	}
	
	public function initData(){		
		$this->path[] =& $this->data;
		return $this;
	}
	
	public function openNode($name){		
		$current =& $this->path[count($this->path) - 1];
		if(!isset($current[$name])) {
			$current[$name] = '';
			$this->path[] =& $current[$name];
		}
		else{
			if(!is_array($current[$name]) || !is_integer(key($current[$name]))){
				$tmp = $current[$name];
				$current[$name] = array();
				$current[$name][] =& $tmp;
			}
			$current[$name][] = '';
			$this->path[] =& $current[$name][count($current[$name]) - 1];
		}
		return $this;
	}
	
	public function closeNode($name){
		array_pop($this->path);
		return $this;
	}
	
	public function setValue($name, $value){
		$current =& $this->path[count($this->path) - 1];
		$current = $value;
		return $this;
	}
}